//
//  KLCurrencyExchangeTableController.m
//  KLCurrency
//
//  Created by apple on 2017/12/2.
//  Copyright © 2017年 bonc. All rights reserved.
//

#import "KLCurrencyExchangeTableController.h"

#import "KLCurrencyHelper.h"
#import "KLCurrencyGroup.h"

#import "KLNumberPad.h"//虚拟键盘
#import "KLCurrencyCell.h"

#import "KLCurrencyEntity.h"
#import "KLArithmeticTextField.h"

#import "KLNavigationController.h"
#import "KLHistoricalRateController.h"
#import "KLCurrencyPickerController.h"

#import "NSString+Arithmetic.h"

#import "KLCurrencyService.h"

#import "KLPlistHelper.h"

#import "KLNetWorkHelper.h"
#import "KLNetWorkService.h"

static const NSInteger defaultUpdateInterval = 600;         //汇率自动更新时间间隔
static const CGFloat indicatorCenterOffsetY = 0.05f;
static const CGFloat kMainRowHeight = 89.5f;

@interface KLCurrencyExchangeTableController ()<UITableViewDataSource, UITableViewDelegate,KLNumberPadDelegate,KLCurrencyCellDelegate, KLCurrencyPickerControllerDelegate, KLHistoricalRateControllerDelegate>

@property (strong, nonatomic) UITableView *tableView;
@property (assign, nonatomic, getter=isFirstLoad) BOOL firstLoad;//用于判断数据是否已经加载过一遍
@property (strong, nonatomic) KLNumberPad *keyboard;//虚拟键盘

//@property (assign, nonatomic) CGFloat mainRowHeight;

@property (strong, nonatomic) NSArray<KLCurrencyEntity *> *mainCurrencyArray;//主界面货币
@property (strong, nonatomic) NSArray *sectionIndexTitles;//货币列表分组标题

@property (strong, nonatomic) KLCurrencyCell *changeCell;//记录切换货币cell
@property (strong, nonatomic) KLCurrencyCell *queryHistoricalRateCell;//记录切换货币cell

@property (strong, nonatomic) KLCurrencyEntity *changeCurrencyEntity;//记录切换货币cell model
@property (strong, nonatomic) KLCurrencyEntity *queryHistoricalRateCurrencyEntity;//记录查询历史汇率货币cell model

@property (assign, nonatomic) NSIndexPath *editingIndexPath;//记录选中的IndexPath
@property (assign, nonatomic) NSIndexPath *changingIndexPath;//记录正在改变的IndexPath
@property (assign, nonatomic) NSIndexPath *queryHistoricalRateIndexPath;//记录正在改变的IndexPath

@property (assign, nonatomic) BOOL changeCurrency;//是否正在切换货币
@property (assign, nonatomic) BOOL queryHistoricalRate;//是否显示历史详情

@property (copy, nonatomic) NSDictionary *exchangeDictionary;//汇率转换表

@property (strong, nonatomic) NSTimer *timer;

@property (strong, nonatomic) UIActivityIndicatorView *indicator;


@end

@implementation KLCurrencyExchangeTableController

- (NSDictionary *)exchangeDictionary {
    if (_exchangeDictionary == nil) {
        //初始化从磁盘缓存中读取
        _exchangeDictionary = [KLCurrencyService getExchangeRateDictionary];
    }
    return _exchangeDictionary;
}

- (UIActivityIndicatorView *)indicator {
    if (_indicator == nil) {
        _indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        CGPoint center = self.tableView.center;
        _indicator.center = CGPointMake(center.x, center.y - indicatorCenterOffsetY * CGRectGetHeight(self.view.frame));
        [self.tableView addSubview:_indicator];
    }
    return _indicator;
}

#pragma mark - vc life cycle 控制器生命周期
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //静态版暂时不判断
    if (_changeCurrency) {
        //将chosen cell位置复原
        [self recoverChangeCell];
        //清空change
        [self clearChangeCurrency];
    }
    if (_queryHistoricalRate) {
        //将rate cell位置复原
        [self recoverQueryHistoricalRateCell];
        //清空rate标记
        [self clearQueryHistoricalRateCurrency];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.    
    
    //第一次加载数据，默认值为100，默认从本地先获取第一次数据
    [self loadMainCurrencyData];
    //设置UI
    [self setupUI];
    //设置默认选中和默认值
    [self setupAllAmountFirstTime];
    KLLog(@"启动完毕");
    //设置定时器 从网络获取最新数据
    [self setupTimer];
}

- (void)dealloc {
    [_timer invalidate];
    _timer = nil;
}

- (void)setupTimer {
    _timer = [NSTimer scheduledTimerWithTimeInterval:defaultUpdateInterval target:self selector:@selector(getCurrentExchangeRateImmediate) userInfo:nil repeats:YES];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [_timer fire];
    });
}

- (void)getCurrentExchangeRateImmediate {
    [self.indicator startAnimating];
    [self addCover];
    KLLog(@"刷新汇率计时器");
    //从网络获取所有当前汇率数据
    if ([KLNetWorkHelper isExistNetWork]) {
        KLLog(@"可以连接互联网");
        
        [KLNetWorkService getCurrencyLayerLiveRateWithSuccess:^(NSDictionary *rateDictionary) {
            [_indicator stopAnimating];
            [self removeCover];
//            KLLog(@"最新汇率表%@",rateDictionary);
            //更新磁盘缓存数据 异步磁盘缓存
            [KLCurrencyService saveExchangeRateDictionary:rateDictionary completion:^{
                KLLog(@"更新磁盘缓存汇率成功");
            } failure:^(NSString *error) {
                KLLog(@"更新磁盘缓存汇率失败");
            }];
            //更新内存缓存数据
            self.exchangeDictionary = rateDictionary;
            //刷新所有数据显示
            [self updateAllAmount];

        } failure:^(NSString *error) {
            [_indicator stopAnimating];
            [self removeCover];
            KLLog(@"最新汇率表请求错误%@",error);
        }];
    } else {
        [_indicator stopAnimating];
        [self removeCover];
        KLLog(@"不可以连接互联网");
    }
}

- (void)setupUI {
    //导航栏
    [self initNavigationItem];
    //列表
    [self initTableView];
}

- (void)initNavigationItem {
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"汇率转换";
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:18.0],
       NSForegroundColorAttributeName:[UIColor blackColor]}];
}

- (void)initTableView {
    //计算tableView行高，按照比例适配
    CGFloat mainRowHeight = kMainRowHeight * kScreenHeight / 667.0;
    
    CGFloat tableViewY = kNavigationBarHeight + kStatusBarHeight;
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, tableViewY, kScreenWidth, kScreenHeight - tableViewY) style:UITableViewStylePlain];
    tableView.bounces = NO;
    //创建键盘视图
    KLNumberPad *keyboard = [KLNumberPad numberPadView];
    CGFloat keyboardY = kNavigationBarHeight + kStatusBarHeight+ self.mainCurrencyArray.count * mainRowHeight;
    keyboard.frame = CGRectMake(0, keyboardY, kScreenWidth, kScreenHeight - keyboardY);
    keyboard.delegate = self;
    tableView.tableFooterView = keyboard;
    
    tableView.rowHeight = mainRowHeight;
    tableView.estimatedRowHeight = 0;
    
    self.keyboard = keyboard;
    //注册cell
    [tableView registerNib:[UINib nibWithNibName:@"KLCurrencyCell" bundle:nil] forCellReuseIdentifier:@"currency"];
    
    tableView.delegate = self;
    tableView.dataSource = self;
    self.tableView = tableView;
    [self.view addSubview:tableView];
}

- (void)loadMainCurrencyData{
    //******新增加载所有数据
    self.mainCurrencyArray = [KLCurrencyService getMainCurrencyEntities];
}

- (void)setupAllAmountFirstTime {
    //加载所有本地汇率数据
    NSIndexPath *firstIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    self.editingIndexPath = firstIndexPath;
    [self.tableView selectRowAtIndexPath:firstIndexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
    KLCurrencyCell *firstCell = [self.tableView cellForRowAtIndexPath:firstIndexPath];
    [firstCell amountInputDidBecomeFirstResponder];
    //刷新所有amount值
    [self updateAllAmount];
}


#pragma mark - table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.mainCurrencyArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KLCurrencyCell *cell = [KLCurrencyCell cellWithTableView:tableView];
    KLCurrencyEntity *currencyEntity = self.mainCurrencyArray[indexPath.row];
    cell.currencyEntity = currencyEntity;
    cell.delegate = self;
    return cell;
}

#pragma mark - table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //清空之前选中的cell的内容
    if (_editingIndexPath == indexPath) {
        return;
    } else {
        [self clearPreviousEditingCellArithmeticText];
        self.editingIndexPath = indexPath;
        
        KLCurrencyCell *editingCell = [self.tableView cellForRowAtIndexPath:self.editingIndexPath];
        [editingCell amountInputDidBecomeFirstResponder];
        
        KLCurrencyEntity *currencyEntity = self.mainCurrencyArray[indexPath.row];
        
        if ([currencyEntity.amount isEqualToString:@""] || currencyEntity.amount == nil) {
            //如果没有数据，要对placeholder进行处理
            [self updateAllAmount];
        }
    }
}

#pragma mark - cell&section height
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return self.mainRowHeight;
//}

#pragma mark - cell delegate
#pragma mark - goto currecny historical rate line
//右划查看汇率曲线
- (void)showCurrencyDetail:(KLCurrencyCell *)cell {
    //记录选中
    self.queryHistoricalRateCell = cell;
    self.queryHistoricalRate = YES;
    
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    self.queryHistoricalRateIndexPath = indexPath;
    KLCurrencyEntity *currencyEntity = self.mainCurrencyArray[indexPath.row];
    currencyEntity.showingHistoricalRate = YES;
    self.queryHistoricalRateCurrencyEntity = currencyEntity;
    
    KLHistoricalRateController *his = [[KLHistoricalRateController alloc] init];
    his.delegate = self;
    his.exchangeCurrency = currencyEntity.abbreviation;
    KLNavigationController *nav = (KLNavigationController *)self.navigationController;
    [nav addFullScreenPopBlackListItem:his];
    [nav pushViewController:his animated:YES];
}

- (void)popHistoricalRateController {

}

- (void)recoverQueryHistoricalRateCell {
    CGPoint center = CGPointMake(self.view.center.x, self.queryHistoricalRateCell.center.y);
    [UIView animateWithDuration:kCellSpringAnimationDuration delay:kCellSpringAnimationDelay usingSpringWithDamping:kCellSpringAnimationDamping initialSpringVelocity:kCellSpringAnimationInitialVelocity options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.queryHistoricalRateCell.center = center;
    } completion:nil];
}

- (void)clearQueryHistoricalRateCurrency {
    self.queryHistoricalRateCell = nil;
    self.queryHistoricalRate = NO;
    self.queryHistoricalRateIndexPath = nil;
    self.queryHistoricalRateCurrencyEntity.showingHistoricalRate = NO;
    self.queryHistoricalRateCurrencyEntity = nil;
}

#pragma mark - goto currecny picker
//左划切换货币
- (void)changeCurrency:(KLCurrencyCell *)cell {
    //记录选中
    self.changeCell = cell;
    self.changeCurrency = YES;
    
    NSIndexPath *changingIndexPath = [self.tableView indexPathForCell:cell];
    self.changingIndexPath = changingIndexPath;
    KLCurrencyEntity *changingCurrencyEntity = self.mainCurrencyArray[changingIndexPath.row];
    changingCurrencyEntity.changing = YES;
    self.changeCurrencyEntity = changingCurrencyEntity;
    
    KLCurrencyPickerController *picker = [[KLCurrencyPickerController alloc] init];
    picker.delegate = self;
    picker.changeCurrencyEntity = changingCurrencyEntity;
    
    picker.changingIndex = changingIndexPath.row;
    
    [self.navigationController pushViewController:picker animated:YES];
}

#pragma mark - picker delegate
- (void)chosenCurrency:(KLCurrencyEntity *)currency {
    if (currency != nil) {
        if (self.changingIndexPath == self.editingIndexPath) {
            //如果更新的是编辑cell，直接全部更新， 默认数据清空
            self.mainCurrencyArray = [KLCurrencyService getMainCurrencyEntities];
        } else {
            //这边保留之前的amount和arithmeticText
            //从原来的mainCurrencyArray取出editingAmount
            KLCurrencyEntity *editingEntity = self.mainCurrencyArray[self.editingIndexPath.row];
            NSMutableArray *tempMainCurrencyArray = [[KLCurrencyService getMainCurrencyEntities] mutableCopy];
            //将editing的值赋值到最新的mainCurrencyArray中
            [tempMainCurrencyArray replaceObjectAtIndex:self.editingIndexPath.row withObject:editingEntity];
            self.mainCurrencyArray = [tempMainCurrencyArray mutableCopy];
        }
        //刷新cell 刷新cell之后动画就没了，解决方法直接赋值
        //        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:self.changingIndexPath, nil] withRowAnimation:UITableViewRowAnimationFade];
        //采用主动给cell赋值刷新方法
        self.changeCell.currencyEntity = currency;
        //刷新数据
        [self updateAllAmount];
    }
}

- (void)clearChangeCurrency {
    self.changeCell = nil;
    self.changeCurrency = NO;
    self.changingIndexPath = nil;
    self.changeCurrencyEntity.changing = NO;
    self.changeCurrencyEntity = nil;
}

- (void)recoverChangeCell {
    CGPoint center = CGPointMake(self.view.center.x, self.changeCell.center.y);
    [UIView animateWithDuration:kCellSpringAnimationDuration delay:kCellSpringAnimationDelay usingSpringWithDamping:kCellSpringAnimationDamping initialSpringVelocity:kCellSpringAnimationInitialVelocity options:UIViewAnimationOptionCurveEaseInOut animations:^{
        self.changeCell.center = center;
    } completion:nil];
    
}

#pragma mark - number pad delegate
- (void)addInput:(NSString *)input {
    KLLog(@"input--%@",input);
    KLLog(@"self.editingIndexPath.row--%ld",self.editingIndexPath.row);
    
    KLCurrencyCell *editingCell = [self.tableView cellForRowAtIndexPath:self.editingIndexPath];
    
    //第一步 判断输入是否是运算符
    KLCurrencyEntity *editingCurrencyEntity = self.mainCurrencyArray[self.editingIndexPath.row];
    NSString *editingAmount = editingCurrencyEntity.amount;
    NSString *editingArithmeticText = editingCurrencyEntity.arithmeticText;

    if ([kOperators containsObject:input] || [NSString containOperatorInString:editingArithmeticText]) {
        // ArithmeticText Input 启动
        [editingCell arithmeticInputDidBecomeFirstResponder];
        
        BOOL illegalEquation = [NSString illegalArithmeticText:editingArithmeticText withInput:input];
        if (illegalEquation) {
            [editingCell arithmeticIllegalInputAnimation];
        } else {
            NSString *newArithmeticText = [NSString changeArithmeticText:editingArithmeticText withInput:input];
            //修改算术式显示
            editingCell.arithmeticInputText = newArithmeticText;
            //修改算术式模型
            editingCurrencyEntity.arithmeticText = newArithmeticText;
            //修改amount显示
            NSString *calculationResult = [NSString calculateArithmeticTextValue:newArithmeticText];
            editingCell.amountInputText = [NSString convertToDecimalStyleWithTwoDigitsFromString:calculationResult];
            //修改算术式模型
            editingCurrencyEntity.amount = calculationResult;
            
            [self updateAllAmount];
        }
    } else {
        //单纯的amount判断 Amount Input 启动
        [editingCell amountInputDidBecomeFirstResponder];
        KLLog(@"editingAmount-%@",editingAmount);
        BOOL illegale = [NSString illegalSingleNumber:editingAmount withInput:input];
        if (illegale == YES) {
            [editingCell amountIllegalInputAnimation];
        } else {
            NSString *result = [NSString changeSingleNumber:editingAmount withInput:input];
            KLLog(@"result--%@",result);
            //修改显示
            editingCell.amountInputText = [NSString convertToDecimalStyleFromEditingString:result];
            editingCell.arithmeticInputText = nil;
            //修改模型
            editingCurrencyEntity.amount = result;
            editingCurrencyEntity.arithmeticText = result;
            
            //根据汇率刷新
            [self updateAllAmount];
        }
    }
}

//清空输入数字和算式
- (void)clearInput {
    KLCurrencyEntity *editingCurrencyEntity = self.mainCurrencyArray[self.editingIndexPath.row];
    KLCurrencyCell *editingCell = [self.tableView cellForRowAtIndexPath:self.editingIndexPath];
    [editingCell amountInputDidBecomeFirstResponder];
    //清空抖动提示
    [editingCell amountIllegalInputAnimation];
    //修改显示
    editingCell.amountInputText = nil;
    editingCell.amountInputPlaceholder = kDefaultAmountText;
    editingCell.arithmeticInputText = nil;
    //修改模型
    editingCurrencyEntity.amount = nil;
    editingCurrencyEntity.arithmeticText = nil;
    //根据汇率刷新
    [self updateAllAmount];
}

- (void)clearPreviousEditingCellArithmeticText {
    KLCurrencyEntity *editingCurrencyEntity = self.mainCurrencyArray[self.editingIndexPath.row];
    KLCurrencyCell *editingCell = [self.tableView cellForRowAtIndexPath:self.editingIndexPath];
    //修改显示
    editingCell.arithmeticInputText = nil;
    //修改模型
    editingCurrencyEntity.arithmeticText = nil;
}

- (void)clearAllCellAmount {
    for (KLCurrencyEntity *currencyEntity in self.mainCurrencyArray) {
        //修改模型
        currencyEntity.amount = nil;
        currencyEntity.arithmeticText = nil;
    }
    
    for (KLCurrencyCell *cell in self.tableView.visibleCells) {
        cell.amountInputText = nil;
        cell.arithmeticInputText = nil;
    }
}

- (void)updateAllAmount {
    KLCurrencyEntity *editingCurrencyEntity = self.mainCurrencyArray[self.editingIndexPath.row];
    editingCurrencyEntity.editing = YES;
    NSString *editingAmount = editingCurrencyEntity.amount;
    
    if ([editingAmount isEqualToString:@""]||editingAmount == nil) {
        //如果没有任何输入 只做placeholder修改 清空模型缓存
        for (KLCurrencyCell *cell in self.tableView.visibleCells) {
            NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
            if (indexPath == self.editingIndexPath) {
                //修改显示
                cell.amountInputPlaceholder = kDefaultAmountText;
                cell.amountInputText = nil;
                cell.arithmeticInputText = nil;
                //修改模型
                editingCurrencyEntity.amount = nil;
                editingCurrencyEntity.arithmeticText = nil;
            }else{
                NSString *ab1 = editingCurrencyEntity.abbreviation;
                KLCurrencyEntity *currencyEntity = self.mainCurrencyArray[indexPath.row];
                currencyEntity.editing = NO;
                NSString *ab2 = currencyEntity.abbreviation;
                CGFloat exchangeAmountValue = kDefaultAmount * [KLCurrencyHelper getCurrencyLayerExchangeRateFromCurrency1:ab1 toCurrency2:ab2 rateDictionary:self.exchangeDictionary];
                NSString *exchangeAmountStr = [NSString stringWithFormat:@"%.2f",exchangeAmountValue];
                //修改显示
                cell.amountInputPlaceholder = exchangeAmountStr;
                cell.amountInputText = nil;
                cell.arithmeticInputText = nil;
                //修改模型
                currencyEntity.amount = nil;
                currencyEntity.arithmeticText = nil;
            }
        }
    } else if (editingAmount.length>0 && fabsf(editingAmount.floatValue) > kMinFloat){
        for (KLCurrencyCell *cell in self.tableView.visibleCells) {
            NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
            if (indexPath != self.editingIndexPath) {
                NSString *ab1 = editingCurrencyEntity.abbreviation;
    
                #if CGFLOAT_IS_DOUBLE
                    CGFloat value1 = editingAmount.doubleValue;
                #else
                    CGFloat value1 = editingAmount.floatValue;
                #endif
                
                KLCurrencyEntity *currencyEntity = self.mainCurrencyArray[indexPath.row];
                currencyEntity.editing = NO;
                NSString *ab2 = currencyEntity.abbreviation;
                CGFloat exchangeAmountValue = value1 * [KLCurrencyHelper getCurrencyLayerExchangeRateFromCurrency1:ab1 toCurrency2:ab2 rateDictionary:self.exchangeDictionary];
                NSString *exchangeAmountStr = [NSString stringWithFormat:@"%.2f",exchangeAmountValue];
                cell.amountInputText = [NSString convertToDecimalStyleWithTwoDigitsFromString:exchangeAmountStr];
                //修改模型
                currencyEntity.amount = exchangeAmountStr;
                currencyEntity.arithmeticText = exchangeAmountStr;
            } else {

            }
        }
    } else if (editingAmount.length>0 && fabsf(editingAmount.floatValue) < kMinFloat) {
        for (KLCurrencyCell *cell in self.tableView.visibleCells) {
            NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
            if (indexPath != self.editingIndexPath) {
                KLCurrencyEntity *currencyEntity = self.mainCurrencyArray[indexPath.row];
                currencyEntity.editing = NO;
                cell.amountInputText = @"0.00";
                //修改模型
                currencyEntity.amount = @"0.00";
                currencyEntity.arithmeticText = @"0.00";
            } else {
                
            }
        }
    } else {
        //exception
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
